package jxtend.processor.eclipse.visitor.handler.impl;

import jxtend.annotation.keyword.override;
import jxtend.processor.eclipse.utils.EclipseProcessorUtils;
import jxtend.processor.eclipse.visitor.handler.ASTNodeHandlerVisitorContext;
import jxtend.processor.eclipse.visitor.handler.AbstractASTNodeVisitorHandler;

import org.eclipse.jdt.internal.compiler.ast.ASTNode;
import org.eclipse.jdt.internal.compiler.ast.MarkerAnnotation;
import org.eclipse.jdt.internal.compiler.ast.MethodDeclaration;
import org.eclipse.jdt.internal.compiler.ast.QualifiedTypeReference;
import org.eclipse.jdt.internal.compiler.lookup.CompilationUnitScope;
import org.eclipse.jdt.internal.compiler.lookup.Scope;
import org.eclipse.jdt.internal.compiler.lookup.TagBits;

@SuppressWarnings("restriction")
public class OverrideAnnotationHandler extends AbstractASTNodeVisitorHandler {

	@Override
	public boolean endVisitBeforeResolve(ASTNodeHandlerVisitorContext context, ASTNode node, Scope scope) {
		if (!(node instanceof MarkerAnnotation)
				|| !(((MarkerAnnotation) node).type instanceof QualifiedTypeReference)
				|| !EclipseProcessorUtils.compoundNameEquals(
						((QualifiedTypeReference) ((MarkerAnnotation) node).type).tokens, override.class)
				|| !(context.getParentNode() instanceof MethodDeclaration)
				|| (scope instanceof CompilationUnitScope)) {
			return true;
		}

		MarkerAnnotation jxtendOverrideAnnotation = (MarkerAnnotation) node;

		MarkerAnnotation javaLangOverrideAnnotation = OverrideAnnotationUtils.createJavaLangOverrideAnnotation(context,
				jxtendOverrideAnnotation.sourceStart, jxtendOverrideAnnotation.sourceEnd, scope);
		javaLangOverrideAnnotation.declarationSourceEnd = jxtendOverrideAnnotation.declarationSourceEnd;

		MethodDeclaration methodDeclaration = (MethodDeclaration) context.getParentNode();
		if (methodDeclaration.binding != null) {
			methodDeclaration.binding.tagBits |= TagBits.AnnotationOverride;
		}

		context.replaceNode(javaLangOverrideAnnotation);

		return true;
	}
}

